package com.changgou.filter;

import com.alibaba.fastjson.JSON;
import com.changgou.util.JwtUtil;
import io.jsonwebtoken.Claims;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.HttpCookie;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.util.HashMap;
import java.util.Map;

/**网关全局过滤器（用于获取令牌信息，并鉴权）
 * @author zhengjd
 * @date 2020/5/15 10:30
 */
@Component
public class AuthorizeFilter implements GlobalFilter, Ordered {

    //令牌头名字
    private static final String AUTHORIZE_TOKEN = "Authorization";
    private static final String LOGIN_URL = "http://localhost:9001/oauth/login";
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {

        //获取请求与响应对象
        ServerHttpRequest request = exchange.getRequest();
        ServerHttpResponse response = exchange.getResponse();
        //1.判断请求是否访问登录微服务，是，则放行
        String path = request.getURI().getPath();
        if (path.startsWith("/api/user/login")){
            return chain.filter(exchange);
        }
        //2.判断是否有token
        //获取头文件中的信息
        String token = request.getHeaders().getFirst(AUTHORIZE_TOKEN);

        //如果没有，则从请求参数中获取
        if (StringUtils.isEmpty(token)){
            token = request.getQueryParams().getFirst(AUTHORIZE_TOKEN);
        }

        //如果没有，从cookie中获取
        if (StringUtils.isEmpty(token)){
            HttpCookie cookie = request.getCookies().getFirst(AUTHORIZE_TOKEN);
            if (cookie!=null){
                token = cookie.getValue();
            }
        }

        if (StringUtils.isEmpty(token)){
            //token为空,设置错误响应状态码
            //response.setStatusCode(HttpStatus.UNAUTHORIZED);
            //登录功能：设置跳转到认证微服务登录界面,并将当前用户所请求的页面传递到认证服务器的登录请求中
            response.getHeaders().set("Location",LOGIN_URL+"?FROM="+request.getURI().toString());
            response.setStatusCode(HttpStatus.SEE_OTHER);   //设置响应状态码为303，为请求跳转
            return response.setComplete();
        }

        //到这里，token不为空，解析token
        try {
            //校验令牌
            /*Claims claims = JwtUtil.parseJWT(token);
            Map<String, Object> map = new HashMap<>();
            map.put("设置","头信息");*/
            //将解析到的jwt成json格式的数据，设置到请求头中
            //request.mutate().header(AUTHORIZE_TOKEN,claims.toString(), JSON.toJSONString(map));
            //将解析到的令牌放入到Header中
            request.mutate().header(AUTHORIZE_TOKEN,"Bearer "+token);
        } catch (Exception e) {
            e.printStackTrace();
            //解析出现异常
            response.setStatusCode(HttpStatus.UNAUTHORIZED);
        }

        //解析无异常，放行
        return chain.filter(exchange);
    }

    @Override
    public int getOrder() {
        return 0;
    }
}
